//
//  M1AnonymousReportVC.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/18.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1AnonymousReportVC.h"
#import "M1FeedbackCell.h"

@interface M1AnonymousReportVC ()<UITextViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    NSInteger m1_max_Num_TextView;
}
@property (nonatomic, strong) UITextView *m1_textView;

@property (nonatomic, strong) UILabel *m1_placeholder;

@property (nonatomic, strong) UILabel *m1_number;

@property (nonatomic, strong) UICollectionView *m1_collectionView;

@property (nonatomic, strong) NSMutableArray *m1_photoArr;

@property (nonatomic, strong) UIButton *m1_commitBtn;

@end

@implementation M1AnonymousReportVC

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange:) name:UITextViewTextDidChangeNotification object:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"匿名举报";
    
    m1_max_Num_TextView = 100;
    
    self.m1_photoArr = [NSMutableArray arrayWithCapacity:0];
    
    [self m1_createUI];
    
}

- (void) m1_commitAction:(UIButton *)sender{
    
    NSString *text = self.m1_textView.text;
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if ([text length] <= 10) {
        [M1Alert m1_alertWithTitle:nil message:@"请写下不少于10字的举报理由"];
        return;
    }
    
    NSDictionary *params;
    if (self.m1_photoArr.count <= 0) {
        params = @{@"to_uid":self.uid,
                   @"remark":self.m1_textView.text,
                   };
    }else{
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.m1_photoArr
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];
        params = @{@"to_uid":self.uid,
                   @"remark":self.m1_textView.text,
                   @"pic":jsonData
                   };
    }
    
    
    WEAKSELF
    [M1HttpNet requestWithMethod:m1_user_inform_url params:params success:^(id resDic, NSInteger code, NSString *message) {
        [M1Alert m1_alertWithTitle:nil message:@"举报成功" buttonTitles:@[@"确定"] action:^(NSInteger index) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        
    } fail:^(id resDic, NSInteger code, NSString *message) {
        
    } showAni:YES];
}

#pragma mark - collectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == self.m1_photoArr.count) {
        [self.m1_textView resignFirstResponder];
        [self m1_choosePhoto];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger numberOfItem = 0;
    if (self.m1_photoArr.count >= 6) {
        numberOfItem = 6;
    }else{
        numberOfItem = self.m1_photoArr.count + 1;
    }
    return numberOfItem;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    M1FeedbackCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCellIdentifier" forIndexPath:indexPath];
    
    if (indexPath.item == self.m1_photoArr.count && self.m1_photoArr.count != 6) {
        cell.m1_photoImage.image = [UIImage imageNamed:@"home_icon_addPhoto"];
    }else{
        [cell.m1_photoImage sd_setImageWithURL:[NSURL URLWithString:self.m1_photoArr[indexPath.item][@"pic"]] placeholderImage:LOAD_LOCAL_IMG(@"bgView")];
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(80, 80);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    CGFloat spacing = 0.0;
    if (SCREENWIDTH < 375) {
        spacing = (SCREENWIDTH - 30 - 240) / 2;
    }else{
        spacing = (SCREENWIDTH - 30 - 320) / 3;
    }
    return spacing;
}


#pragma mark - textViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    if ([textView.text length] > 0) {
        self.m1_placeholder.hidden = YES;
    }else{
        self.m1_placeholder.hidden = NO;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}



-(void)textChange:(NSNotification *)note{
    
    //获取当前键盘类型
    UITextInputMode *mode = (UITextInputMode *)[UITextInputMode activeInputModes][0];
    
    //获取当前键盘语言
    NSString *lang = mode.primaryLanguage;
    
    //如果语言是汉语(拼音)
    if ([lang isEqualToString:@"zh-Hans"])
    {
        //取到高亮部分范围
        UITextRange *selectedRange = [self.m1_textView markedTextRange];
        //取到高亮部分
        UITextPosition *position = [self.m1_textView positionFromPosition:selectedRange.start offset:0];
        //如果取不到高亮部分,代表没有拼音
        if (!position){
            //当期超过最大限制时
            if (self.m1_textView.text.length > m1_max_Num_TextView) {
                
                //对超出部分进行裁剪
                self.m1_textView.text = [self.m1_textView.text substringToIndex:m1_max_Num_TextView];
                
                //同时将下方提示label设置为0
                self.m1_number.text = [NSString stringWithFormat:@"%ld/%ld", m1_max_Num_TextView, m1_max_Num_TextView];
            }
            
            //如果没超出,那么就计算字数
            self.m1_number.text = [NSString stringWithFormat:@"%ld/%ld", [self.m1_textView.text length], m1_max_Num_TextView];
        }else{
            //表示还有高亮部分，暂不处理
        }
        
    }else{
        //如果语言不是汉语,直接计算
        if (self.m1_textView.text.length > m1_max_Num_TextView) {
            
            self.m1_textView.text = [self.m1_textView.text substringToIndex:m1_max_Num_TextView];
            
            self.m1_number.text = [NSString stringWithFormat:@"%ld/%ld", m1_max_Num_TextView, m1_max_Num_TextView];
        }
        
        self.m1_number.text = [NSString stringWithFormat:@"%ld/%ld", [self.m1_textView.text length], m1_max_Num_TextView];
    }
}

- (void)m1_choosePhoto{
    if (self.m1_photoArr.count >=9) {
        [M1Alert m1_alertWithTitle:nil message:@"最多选择9张张片"];
        return;
    }
    
    M1SheetView *m1_sheet = [[M1SheetView alloc]initWithTitles:@[@"拍照",@"从相册选择"]];
    [m1_sheet m1_show];
    
    WEAKSELF
    m1_sheet.click = ^(NSInteger index) {
        [[M1ImagePick manager] m1_pickImages:^(NSArray *photos) {
            [[M1FileUpload manager] m1_uploadImages:photos progress:^(CGFloat progress) {
                
            } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
                for (NSString *image in urls) {
                    [weakSelf.m1_photoArr addObject:@{@"pic":image}];
                }
                [weakSelf m1_changeCollectionView];
                
            }];
        } type:index maxCount:6-self.m1_photoArr.count vc:weakSelf];
    };
}


#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // * 照片
    //
    if ([info objectForKeyedSubscript:@"UIImagePickerControllerOriginalImage"])
    {
        UIImage *image = [info objectForKeyedSubscript:@"UIImagePickerControllerOriginalImage"];
        
        WEAKSELF
        [[M1FileUpload manager] m1_uploadImages:@[image] progress:^(CGFloat progress) {
            
        } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
            [weakSelf.m1_photoArr addObject:@{@"pic":[urls firstObject]}];
        }];
    }
    
    [self m1_changeCollectionView];
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (void) m1_createUI{
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = m1_color(0xFFFFFF);
    [self.view addSubview:bgView];
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(m1_NAV_HEIGHT);
        make.height.offset(160);
    }];
    
    self.m1_textView = [[UITextView alloc] init];
    _m1_textView.textColor = m1_color(0x333333);
    _m1_textView.font = m1_font(15);
    _m1_textView.delegate = self;
    [bgView addSubview:_m1_textView];
    
    [_m1_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(15, 20, 15, 20));
    }];
    
    self.m1_placeholder = [[UILabel alloc] init];
    _m1_placeholder.text = @"请写下不少于10字的举报理由(必填)";
    _m1_placeholder.textColor = m1_color(0x999999);
    _m1_placeholder.font = m1_font(15);
    _m1_placeholder.numberOfLines = 0;
    [bgView addSubview:_m1_placeholder];
    
    [_m1_placeholder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(22);
        make.left.mas_equalTo(23);
        make.right.mas_equalTo(-23);
    }];
    
    self.m1_number = [[UILabel alloc] init];
    _m1_number.text = @"0/100";
    _m1_number.textColor = m1_color(0xCCCCCC);
    _m1_number.font = m1_font(15);
    [self.view addSubview:_m1_number];
    
    [_m1_number mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgView.mas_bottom).offset(10);
        make.right.offset(-20);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"上传截图，提高举报准确度";
    label.textColor = m1_color(0x999999);
    label.font = m1_font(12);
    [self.view addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(19);
        make.top.equalTo(bgView.mas_bottom).offset(41);
    }];
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"鼓励上传微信等其他平台聊天记录截图"];
    
    [text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, 2)];
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.textColor = m1_color(0x999999);
    label1.attributedText = text;
    label1.font = m1_font(12);
    [self.view addSubview:label1];
    
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(19);
        make.top.equalTo(label.mas_bottom).offset(9);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.m1_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, m1_NAV_HEIGHT + 160 + 95, SCREENWIDTH, 80) collectionViewLayout:layout];
    self.m1_collectionView.backgroundColor = [UIColor clearColor];
    self.m1_collectionView.delegate = self;
    self.m1_collectionView.dataSource = self;
    self.m1_collectionView.scrollEnabled = NO;
    [self.view addSubview:self.m1_collectionView];
    
    [self.m1_collectionView registerClass:[M1FeedbackCell class] forCellWithReuseIdentifier:@"CollectionViewCellIdentifier"];
    
    self.m1_commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_m1_commitBtn setBackgroundImage:LOAD_LOCAL_IMG(@"btn_color") forState:UIControlStateNormal];
    _m1_commitBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [_m1_commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [_m1_commitBtn setTitleColor:m1_color(0xFFFFFF) forState:UIControlStateNormal];
    _m1_commitBtn.titleLabel.font = m1_font(18);
    [_m1_commitBtn addTarget:self action:@selector(m1_commitAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_m1_commitBtn];
    
    _m1_commitBtn.layer.cornerRadius = 55 / 2;
    _m1_commitBtn.layer.masksToBounds = YES;
    
    [_m1_commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.offset(iPhone5?-10:-50);
        make.size.mas_equalTo(CGSizeMake(170, 55));
    }];
    
}

- (void)m1_changeCollectionView{
    if (SCREENWIDTH < 375) {
        if (self.m1_photoArr.count >= 3 && self.m1_photoArr.count <= 5) {
            self.m1_collectionView.frame = CGRectMake(0, m1_NAV_HEIGHT + 160 + 95, SCREENWIDTH, 170);
        }else if (self.m1_photoArr.count >= 6){
            self.m1_collectionView.frame = CGRectMake(0, m1_NAV_HEIGHT + 160 + 95, SCREENWIDTH, 260);
        }
    }else{
        if (self.m1_photoArr.count >= 4 && self.m1_photoArr.count <= 7) {
            self.m1_collectionView.frame = CGRectMake(0, m1_NAV_HEIGHT + 160 + 95, SCREENWIDTH, 170);
        }else if (self.m1_photoArr.count >= 8){
            self.m1_collectionView.frame = CGRectMake(0, m1_NAV_HEIGHT + 160 + 95, SCREENWIDTH, 260);
        }
    }
    
    [self.m1_collectionView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
